#!/bin/sh

DATE=`date "+%Y%m%d"`
VMS='Jenkins-Server'
LOGFILE=/home/joevnc/VM-Backup/logs/export_${DATE}.log

#trap 'echo "Execute line: $LINENO" ' DEBUG

# Export VMs for backup 
for vm in  $VMS
do
   if [ `VBoxManage list runningvms|grep $vm |wc -l` -eq 1 ]; then
      echo "`date +"%F %H:%M:%S"` Begin to shutdown vm ${vm} ... " >> ${LOGFILE}
      VBoxManage controlvm $vm poweroff

      if [ $? -eq 0  ];then
         echo "`date +"%F %H:%M:%S"` Begin to export vm ${vm} ..." >> ${LOGFILE}
         VBoxManage export $vm -o /home/joevnc/VM-Backup/data/${vm}_${DATE}.ova
      else
         echo "`date +"%F %H:%M:%S"` Shutdown vm ${vm} failed !!!" >> ${LOGFILE}
         exit 1
      fi

      echo "`date +"%F %H:%M:%S"` Begin to start vm ${vm} ... " >> ${LOGFILE}
      VBoxManage startvm $vm
      if [ $? -ne 0  ];then
         echo "`date +"%F %H:%M:%S"` Start vm ${vm} failed !!!" >> ${LOGFILE} 
      fi     
   else
      echo "`date +"%F %H:%M:%S"` Begin to export vm ${vm} ..." >> ${LOGFILE}
      VBoxManage export $vm -o /home/joevnc/VM-Backup/data/${vm}_${DATE}.ova
  
      echo "`date +"%F %H:%M:%S"` Begin to start vm ${vm} ... " >> ${LOGFILE}
      VBoxManage startvm $vm
      if [ $? -ne 0  ];then
         echo "`date +"%F %H:%M:%S"` Start vm ${vm} failed !!!" >> ${LOGFILE}   
      fi
   fi
done

# Copy files to another server for bakcup
echo "                                                                    " >> ${LOGFILE}
echo "`date +"%F %H:%M:%S"` Begin to copy backup files to 192.168.2.40 ..." >> ${LOGFILE}
scp /home/joevnc/VM-Backup/data/*_${DATE}.ova root@192.168.2.40:/home/joevnc/VM-Backup/data/backup30
echo "`date +"%F %H:%M:%S"` Copy files finished .                         " >> ${LOGFILE}

# Remove 7 days ago backup files
echo "                                                                    " >> ${LOGFILE}
echo "Below backup files will be removed:                                 " >> ${LOGFILE}
find /home/joevnc/VM-Backup/data -name "*.ova" -mtime +6 -exec ls -al {} \; >> ${LOGFILE}
find /home/joevnc/VM-Backup/data -name "*.ova" -mtime +6 -exec rm -rfv {} \;

# Remove 7 days ago log files
echo "                                                                    " >> ${LOGFILE}
echo "Below log files will be removed:                                    " >> ${LOGFILE}
find /home/joevnc/VM-Backup/logs -name "*.log" -mtime +6 -exec ls -al {} \; >> ${LOGFILE}
find /home/joevnc/VM-Backup/logs -name "*.log" -mtime +6 -exec rm -rfv {} \;
